package voloshyn.paliy.camera;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;

public class BluetoothCameraSocket extends Thread {
    private static final String UUID_STR = "38fa6170-0292-11e2-a21f-0800200c9a66";
    private byte[] frameToSend = null;
    private OutputStream stream = null;
    private BluetoothSocket remoteSocket = null;
    private BluetoothServerSocket serverSocket = null;
    private boolean isConnected = true;
    private ConnectHandler connectHandler = new ConnectHandler();
    private BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    
    public void setOnConnectListener(OnConnectListener theConnectListener) {
	connectHandler.setOnConnectListener(theConnectListener);
    }

    private void initSocket() throws IOException {
	UUID cameraUUID = UUID.fromString(UUID_STR);
	serverSocket = adapter.listenUsingRfcommWithServiceRecord(
		"CameraActivity", cameraUUID);
	remoteSocket = serverSocket.accept();
	stream = remoteSocket.getOutputStream();
	serverSocket.close();
	serverSocket = null;
    }

    @Override
    public void run() {

	try {
	    initSocket();
	    isConnected=true;
	    while (isConnected) {
		if (frameToSend != null) {
		    stream.write(frameToSend);
		    stream.flush();
		    frameToSend = null;
		} else {
		    Thread.sleep(10);
		}
	    }
	    closeConnection();
	    connectHandler.handle(ConnectHandler.MESSAGE_DISCONNECT);
	} catch (Throwable e) {
	    closeConnection();
	    connectHandler.handle(ConnectHandler.MESSAGE_DISCONNECT_ERROR);
	}
    }

    private void closeConnection() {
	if (stream != null) {
	    try {
		stream.close();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	    stream = null;
	}
	if (remoteSocket != null) {
	    try {
		remoteSocket.close();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	    remoteSocket = null;
	}
    }

    public void disconnect() {
	isConnected = false;
	if (serverSocket != null) {
	    try {
		serverSocket.close();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	    serverSocket = null;
	}
    }

    public void sendFrame(byte[] input) {
	if (frameToSend == null) {
	    frameToSend = input;
	}
    }
}
